package com.yupi.project.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.apicommon.model.entity.InterfaceInfo;
import com.example.apicommon.model.entity.User;
import com.example.apicommon.model.entity.UserInterfaceInfo;
import com.yupi.project.annotation.AuthCheck;
import com.yupi.project.common.BaseResponse;
import com.yupi.project.common.ErrorCode;
import com.yupi.project.common.ResultUtils;
import com.yupi.project.exception.BusinessException;
import com.yupi.project.mapper.UserInterfaceInfoMapper;
import com.yupi.project.model.dto.interfaceinfo.InterfaceInfoAddRequest;
import com.yupi.project.model.vo.InterfaceInfoVO;
import com.yupi.project.service.InterfaceInfoService;
import com.yupi.project.service.UserInterfaceInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/analysis")
@Slf4j
public class AnalysisController {
    @Resource
    UserInterfaceInfoMapper userInterfaceInfoMapper;
    @Resource
    InterfaceInfoService interfaceInfoService;

    @GetMapping("/top/interface/invoke")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<List<InterfaceInfoVO>> getTopUserInterfaceInfo() {
        //获取调用次数前三的UserInterfaceInfo信息
        List<UserInterfaceInfo> topUserInterInfo = userInterfaceInfoMapper.getTopUserInterInfo(3L);
        //按照接口ID进行分组
        Map<Long, List<UserInterfaceInfo>> collect = topUserInterInfo.stream()
                .collect(Collectors.groupingBy(UserInterfaceInfo::getInterfaceInfoId));
        //查询出对应接口信息
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", collect.keySet());
        List<InterfaceInfo> list = interfaceInfoService.list(queryWrapper);
        //处理接口信息,添加上接口总调用次数
        List<InterfaceInfoVO> InterfaceInfoVOList = list.stream()
                .map(interfaceInfo -> {
                    InterfaceInfoVO interfaceInfoVO = new InterfaceInfoVO();
                    BeanUtils.copyProperties(interfaceInfo, interfaceInfoVO);
                    int totalNum = collect.get(interfaceInfo.getId()).get(0).getTotalNum();
                    interfaceInfoVO.setTotalNum(totalNum);
                    return interfaceInfoVO;
                }).collect(Collectors.toList());

        return ResultUtils.success(InterfaceInfoVOList);
    }


}
